package com.tywj.buscustomerapp.view.item;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.tywj.buscustomerapp.Config;
import com.tywj.buscustomerapp.R;
import com.tywj.buscustomerapp.model.bean.RequesrDaysTicketBean;
import com.tywj.buscustomerapp.model.bean.TravelLineBean;
import com.tywj.buscustomerapp.utils.SPUtils;
import com.tywj.buscustomerapp.utils.TaylorClickLinstener;
import com.tywj.buscustomerapp.utils.WebServicrUtils;
import com.tywj.buscustomerapp.utils.myadapter.item.AdapterItem;
import com.tywj.buscustomerapp.view.activity.BuyTicketsActivity;
import com.tywj.buscustomerapp.view.activity.LoginActivity;
import com.tywj.buscustomerapp.view.activity.MapActivity;
import com.tywj.buscustomerapp.view.activity.PayActivity;
import com.tywj.buscustomerapp.view.activity.newBuyTicketActivity;
import com.tywj.buscustomerapp.view.myview.ToastJoe;

import org.json.JSONException;
import org.json.JSONObject;
import org.xmlpull.v1.XmlPullParserException;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class TravleLineItem implements AdapterItem<TravelLineBean> {

    private TextView tag;
    private TextView lineName;
    private TextView lineTime;
    private TextView lineInfo;
    private TextView lineButton;
    private LinearLayout travel;
    private Context context;
    private ImageView line_travel_img;
    private TextView line_time1;

    @Override
    public int getLayoutResId() {
        return R.layout.item_travel_line;
    }

    @Override
    public void bindViews(@NonNull View root) {
        context = root.getContext();
        tag = root.findViewById(R.id.line_tag);
        lineName = root.findViewById(R.id.line_travel);
        lineTime = root.findViewById(R.id.line_time);
        lineButton = root.findViewById(R.id.line_button);
        lineInfo = root.findViewById(R.id.line_info);
        travel = root.findViewById(R.id.travel);
        line_time1 = root.findViewById(R.id.line_time1);
//        line_travel_img = root.findViewById(R.id.line_travel_img);
    }

    @Override
    public void setViews() {

    }

    @Override
    public void handleData(final TravelLineBean travelLineBean, int position) {
        if (position == 0 || travelLineBean.isDaysTicket){
            tag.setVisibility(View.VISIBLE);
        }else{
            tag.setVisibility(View.GONE);
        }
        if (travelLineBean.isDaysTicket){
            lineName.setText(travelLineBean.getDaysTicket().getName());
            lineTime.setText(travelLineBean.getDaysTicket().getDays()+"天无限次乘坐");
            lineButton.setText("￥" + travelLineBean.getDaysTicket().getPrice() + " 购票");
            lineInfo.setVisibility(View.GONE);
            lineButton.setOnClickListener(new TaylorClickLinstener() {
                @Override
                public void onMultiClick(View v) {
                    String phone = SPUtils.getUserPhone(v.getContext().getApplicationContext());
                    if (phone != null && !phone.equals("")) {
                        doSomthing(phone,travelLineBean.getDaysTicket().getId(),travelLineBean.getDaysTicket().getCityId());
                    } else {
                        Intent intent = new Intent(v.getContext(), LoginActivity.class);
                        v.getContext().startActivity(intent);
                    }
                }
            });
        }else {
            if (travelLineBean.getType().equals("CommuteLine")){
                line_time1.setVisibility(View.VISIBLE);
            }else{
                line_time1.setVisibility(View.GONE);
            }
            lineName.setText(travelLineBean.getName());
            lineInfo.setText(travelLineBean.getStartLocation() + "——" + travelLineBean.getEndLocation());
            lineTime.setText(travelLineBean.getStartTime() + "-" + travelLineBean.getEndTime());
            lineButton.setText("￥" + travelLineBean.getPrice() + " 购票");
            lineButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String phone = SPUtils.getUserPhone(v.getContext().getApplicationContext());
                    if (phone != null && !phone.equals("")) {
                        Intent intent = new Intent(v.getContext(), BuyTicketsActivity.class);
                        intent.putExtra("lineNum", travelLineBean);
                        v.getContext().startActivity(intent);
                    } else {
                        Intent intent = new Intent(v.getContext(), LoginActivity.class);
                        v.getContext().startActivity(intent);
                    }
//                    Intent intent = new Intent(v.getContext(), newBuyTicketActivity.class);
//                    intent.putExtra("lineNum", travelLineBean.getNumber());
//                    v.getContext().startActivity(intent);
                }
            });
            travel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(v.getContext(), MapActivity.class);
                    intent.putExtra("lineNum", travelLineBean);
                    v.getContext().startActivity(intent);
                }
            });
        }
        if (travelLineBean.getType()!=null && travelLineBean.getType().equals("DeliciousFoodLine")){
            line_travel_img.setImageResource(R.mipmap.icon_card_food_line);
        }else{
            line_travel_img.setImageResource(R.mipmap.icon_card_through);
        }
    }

    private void buyDaysTicket(final String gmrq, final String gmje, final String dqrq, final String cplx, final String cs, final String qsrq, final String phone, final TravelLineBean travelLineBean){
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> e){
                try {
                    String msg1 = WebServicrUtils.getInstance().buyDaysTicket(gmrq,gmje,dqrq,cplx,phone,cs,qsrq);
                    String[] msg = msg1.split(",");
                    if (msg[0].equals("ok")){
                        e.onNext(msg[1]);
                    }else{
                        e.onError(null);
                    }
                } catch (IOException e1) {
                    e1.printStackTrace();
                    e.onError(null);
                } catch (XmlPullParserException e1) {
                    e1.printStackTrace();
                    e.onError(null);
                } catch (Exception e1) {
                    e1.printStackTrace();
                    e.onError(null);
                }
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }
                    @Override
                    public void onNext(String s) {
                        Intent intent = new Intent(context, PayActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putInt("position",1);
                        bundle.putSerializable("bean",travelLineBean);
                        bundle.putString("dasTID",s);
                        intent.putExtras(bundle);
                        context.startActivity(intent);
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void doSomthing(String yhm,String cplx,String cs){
        RequestQueue requestQueue = Volley.newRequestQueue(context);
        //创建一个请求
        String url = Config.SBURL + "/order/addCycleOrder";
        JSONObject object = new JSONObject();
        try {
            object.put("yhm",yhm);
            object.put("cplx",cplx);
            object.put("cs",cs);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, object, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                Log.i("taylor",String.valueOf(jsonObject));
                RequesrDaysTicketBean data = new Gson().fromJson(String.valueOf(jsonObject),RequesrDaysTicketBean.class);
                if (data!=null && data.getReCode().equals("201")){
//                    ToastJoe.getmToastJoe().ToastShowRight(context,null,data.getCodeTxt()+"1");
                    Intent intent = new Intent(context, PayActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putInt("position",1);
                    bundle.putSerializable("bean",data);
                    intent.putExtras(bundle);
                    context.startActivity(intent);
//                    context.startActivity(new Intent(context,LoginActivity.class));
                }else{
                    ToastJoe.getmToastJoe().ToastShow(context,null,data.getCodeTxt()+"2");
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
            }
        });
        //将创建的请求添加到队列中
        requestQueue.add(jsonObjectRequest);
    }
}
